<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2020 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\index\controller;

use think\facade\Db;
use think\facade\View;
use app\index\addons\Url;
use app\index\BaseController;
use think\captcha\facade\Captcha;
/**
 * 系统页面
 */
class Page extends BaseController
{
    /**
     * 系统页面
     */
    public function index()
    {
        $name = str_replace('-', '_', $this->request->routeName);
        return is_file(theme_path_now() . $name .'.html') ? View::fetch($name) : View::fetch("404");
    }

    /**
     * api获取基本信息
     */
    public function baseInfo()
    {
        if ($this->request->isPost()) {
            return json(['status' => 'success', 'message' => '请求成功', 'data' => $this->baseInfo]);
        } else {
            return json(['status' => 'success', 'message' => '请求类型不正确，请使用post请求']);
        }
    }

    /**
     * 验证码
     */
    public function verify()
    {
        return Captcha::create();
    }

    /**
     * miss
     */
    public function miss404()
    {
        return View::fetch("404");
    }

    /**
     * 权限不足
     */
    public function miss403()
    {
        return View::fetch("403");   
    }

    /**
     * 全站搜索
     */
    public function search()
    {
        $modularList = [];
        $input = input();
        $modular = isset($input['modular']) ? $input['modular'] : '';
        $keyword = isset($input['keyword']) ? $input['keyword'] : '';
        $page    = isset($input['page']) ? $input['page'] : 1;
        $list    = [];
        $field   = 'id,title,cover,seo_url,seo_description,create_time,status,language';
        $whereStr= 'WHERE status = 1 AND language = "'.$this->request->lang.'" AND title LIKE "%'.$keyword.'%" OR seo_description LIKE "%'.$keyword.'%"';
        $where[] = ['status', '=', 1];
        $where[] = ['language', '=', $this->request->lang];
        $where[] = ['title|seo_description', 'like', '%'.$keyword.'%'];
        $union   = "";
        $count   = 0;
        foreach (plugin_route('single') as $key => $val) {
            $exist = Db::query("SHOW TABLES LIKE 'mk_".$val['table']."'");
            // 查询表存在
            if ($exist) {
                $fieldAll = Db::query("SHOW COLUMNS FROM mk_".$val['table']."");
                $fieldAll = array_column($fieldAll, 'Field');
                $fieldArr = explode(',', $field);
                $fieldExist = true;
                foreach ($fieldArr as $key => $value) {
                    if (! in_array($value, $fieldAll)) {
                        $fieldExist = false;
                    }
                }
                // 查询字段存在（可查询的表）
                if ($fieldExist) {
                    array_push($modularList, $val);
                    // 选择类别（选中类别则只查询此表）
                    if (empty($modular) || str_replace('_catalog', '', $modular) === $val['name']) {
                        // 总数
                        $count = $count + Db::name($val['table'])->where($where)->count();
                        // 拼接union
                        if (empty($union)) {
                            $union = Db::name($val['table'])->field($field.',"'.$val['name'].'" as name')->where($where);
                        } else {
                            $union = $union->unionAll('SELECT '.$field.',"'.$val['name'].'" as name FROM mk_'.$val['table'].' '.$whereStr.'');
                        }
                    }
                }
            }
        }
        // 开始查询
        if (! empty($union)) {
            $pageSize = 10;
            $data = $union->page($page, $pageSize)->select();
            if ($data) {
                $data = $data->toArray();
                foreach ($data as $index => $item) {
                    $item['title']  = str_ireplace($keyword, '<b style="color:#016aac">'.$keyword.'</b>', $item['title']);
                    $item['type']   = $item['name'];
                    $item['url']    = Url::getSingleUrl($item, $item['name']);
                    $item['cover']  = $this->request->domain() . $this->request->root() . $item['cover'];
                    array_push($list, $item);
                }
            }
        }
        View::assign([
            'list'        => $list,
            'page'        => $page,
            'count'       => $count,
            'modular'     => $modular,
            'keyword'     => $keyword,
            'modularList' => $modularList,
        ]);
        return View::fetch('search');
    }
}
